package gw.com.android.ui.news;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigTypesDeal;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.ViewPagerAdapter;
import gw.com.android.ui.views.CommonTitleBar;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;

/**
 * Created by reeta.zou on 2016/8/3.
 * 资讯界面
 */
public class MainNewsFragment extends PushMsgTabFragment {
    @BindView(R.id.main_tab_title_bar)
    CommonTitleBar mTitleBar;

    /** 按钮组 */
    @BindView(R.id.tabs)
    TabLayout mTabLayout;
    @BindView(R.id.viewpager)
    ViewPager mViewPager;

    private DataItemResult mTabTitles;
    private ViewPagerAdapter mAdapter;
    private HashMap<String, PushMsgTabFragment> mFragmentList;
    private PushMsgTabFragment mCurrentFragment = null; // 当前显示的fragment
    private ConfigTypesDeal mTypesDeal;
    private String mCurType;

    public MainNewsFragment() {
    }

    public static MainNewsFragment newInstance(String leftTitle) {
        MainNewsFragment fragment = new MainNewsFragment();
        Bundle args = new Bundle();
        args.putString("leftTitle", leftTitle);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_news;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
    }

    @Override
    protected void initViewData() {
        onSendQuote();
        mTitleBar.setAppTitle(R.string.main_menu_item_new);
        mTypesDeal = new ConfigTypesDeal();
        mTabTitles = mTypesDeal.getNewsTypeList();
        mCurType = mTabTitles.getItem(0).getString(ConfigType.CONFIG_TYPE_TYPE_TAG);
        mFragmentList = new HashMap<String, PushMsgTabFragment>();
        mAdapter = new ViewPagerAdapter(mFragmentManager, mTabTitles, new ViewPagerAdapter.ShowFragmentListener() {
            @Override
            public PushMsgTabFragment showFragment(String type, int position) {
                String title = "";
                if(position >=0 && position < mTabTitles.getDataCount()){
                    DataItemDetail itemDetail = mTabTitles.getItem(position);
                    title = itemDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG);
                }
                return getFragment(title, type, position);
            }
        });
        mViewPager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Logger.e("MainNewsFragment onPageSelected " + position);
                if(position >=0 && position < mTabTitles.getDataCount()){
                    DataItemDetail itemDetail = mTabTitles.getItem(position);
                    mCurType = itemDetail.getString(ConfigType.CONFIG_TYPE_TYPE_TAG);
                    mCurrentFragment = getFragment(itemDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG), mCurType, position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mCurrentFragment = NewsFragment.newInstance(mCurType, mTabTitles.getItem(0).getString(ConfigType.CONFIG_TYPE_TITLE_TAG), mTabTitles.getItem(0).getString(ConfigType.CONFIG_TYPE_KEY_TAG));
        mFragmentList.put(mCurType+"", mCurrentFragment);
    }

    @Override
    public void registerRxBus() {
        super.registerRxBus();
        Disposable getDataRegister = RxBus.getInstance().register(GTSConst.REPLY_HTTP_NEWS_LIST+"", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>(){

                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Bundle bundle) throws Exception {
                        int iValue = bundle.getInt("iValue");
                        String strObject = bundle.getString("strObject");
                        if (null != strObject && strObject.startsWith("{") && strObject.endsWith("}")) {
                            try {
                                JSONObject object = new JSONObject(strObject);
                                String mType = "";
                                if (null != object.optString("type")) {
                                    mType = object.optString("type");
                                }
                                Logger.e("资讯列表 type = " + mType + "iValue = " + iValue);
                                if(mFragmentList.containsKey(mType+"")){
                                    NewsFragment newFragment = (NewsFragment) mFragmentList.get(mType+"");
                                    if(null != newFragment){
                                        newFragment.loadFinish(iValue,strObject);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });

        bindSubscription(getDataRegister);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            BaseActivity activity = (BaseActivity) getActivity();
            if(null != activity){
                activity.setTransparentBar(false);
            }
            onSendQuote();
        }
    }

    @Override
    public void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
    }

    /**
     * 返回当前显示的fragment界面
     */
    private PushMsgTabFragment getFragment(String title, String type, int position){
        if(mFragmentList.containsKey(type+"")){
            Logger.e("MainNewsFragment getFragment type " + type);
            return mFragmentList.get(type+"");
        }else{
            Logger.e("MainNewsFragment getFragment type is new" + type);
            NewsFragment fragment = NewsFragment.newInstance(type, title, mTabTitles.getItem(position).getString(ConfigType.CONFIG_TYPE_KEY_TAG));
            mFragmentList.put(type+"", fragment);
            return fragment;
        }
    }
}
